<?php
namespace app\company\logic;

class Export{
    /**
     * @stone
     * @param $title 标题数组
     * @param $list  数据数组
     * @param $name  excel名称
     * @param int $width
     * @param $text  需要文本的数组 ['A','C']格式
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    static public function excel($title,$list,$name,$width=20,$text=[]){
        set_time_limit(0);
        import('PHPExcel/PHPExcel', EXTEND_PATH);
        $obj = new \PHPExcel();
        //横向单元格标识
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $obj->getActiveSheet(0)->setTitle(date('Y-m-d',time()).$name);   //设置sheet名称
        $_row = 1;   //设置纵向单元格标识
        if($title){
            $i = 0;
            foreach($title AS $v){   //设置列标题
                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);

                $i++;
            }
            $_row++;
        }
        //设置样式
        $count = count($title);
        $max = $cellName[$count-1];

        $obj->getActiveSheet()->getStyle( 'A1:'.$max.'1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        //设置背景样式
        $obj->getActiveSheet()->getStyle( 'A1:'.$max.'1')->getFill()->getStartColor()->setARGB('FF808000');
        //设置单元格格式:文本
        foreach ($text as $key=>$value){
            $obj->getActiveSheet()->getStyle($value)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
        }

        //设置宽度
        foreach ($title as $key=>$value){
            $b = $cellName[$key];
            $obj->getActiveSheet()->getColumnDimension( $b)->setWidth($width);
        }
        if($list){
            $i = 0;
            foreach($list AS $_v){
                foreach ($_v as $key=>$_vv){
                    $obj->getActiveSheet(0)->setCellValue($cellName[$key] . ($i+$_row), $_vv);
                }
                $i++;
            }
        }
        //文件名处理
        $fileName = date('Y-m-d',time()).$name;
        $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
        //网页下载
        header('pragma:public');
        header("Content-Disposition:attachment;filename=$fileName.xlsx");
        $objWrite->save('php://output');exit;
    }

}
